# -*- coding: utf-8 -*-
"""
@ Created on 2024-06-14 12:23
---------
@summary: 异常处理器
---------
@author: Lsaiah
"""

from fastapi import Request, status, HTTPException
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from jose import JWTError
from core.exceptions import CustomHTTPException, AuthenticationException, AuthorizationException
from core.response import ResponseModel
from constant import *
from log import logger


async def custom_http_exception_handler(request: Request, exc: CustomHTTPException):
    """自定义HTTP异常处理器"""
    return JSONResponse(
        status_code=HTTP_200_OK,
        content={
            "code": exc.code,
            "message": exc.message,
            "data": exc.data
        },
        headers=exc.headers
    )


async def authentication_exception_handler(request: Request, exc: AuthenticationException):
    """认证异常处理器"""
    return JSONResponse(
        status_code=HTTP_200_OK,
        content={
            "code": CODE_UNAUTHORIZED,
            "message": exc.message,
            "data": None
        },
        headers={"WWW-Authenticate": "Bearer"}
    )


async def authorization_exception_handler(request: Request, exc: AuthorizationException):
    """授权异常处理器"""
    return JSONResponse(
        status_code=HTTP_200_OK,
        content={
            "code": CODE_FORBIDDEN,
            "message": exc.message,
            "data": None
        }
    )


async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """请求验证异常处理器"""
    errors = []
    for error in exc.errors():
        errors.append({
            "field": " -> ".join(str(loc) for loc in error["loc"]),
            "message": error["msg"],
            "type": error["type"]
        })
    
    return JSONResponse(
        status_code=HTTP_200_OK,
        content={
            "code": CODE_VALIDATION_ERROR,
            "message": "数据验证失败",
            "data": errors
        }
    )


async def jwt_exception_handler(request: Request, exc: JWTError):
    """JWT异常处理器"""
    logger.error(f"JWT处理异常: {str(exc)}")
    return JSONResponse(
        status_code=HTTP_200_OK,
        content={
            "code": CODE_UNAUTHORIZED,
            "message": "无效的认证令牌",
            "data": None
        },
        headers={"WWW-Authenticate": "Bearer"}
    )


async def http_exception_handler(request: Request, exc: HTTPException):
    """HTTP异常处理器"""
    return JSONResponse(
        status_code=HTTP_200_OK,
        content={
            "code": exc.status_code,
            "message": exc.detail,
            "data": None
        },
        headers=exc.headers
    )


async def general_exception_handler(request: Request, exc: Exception):
    """通用异常处理器"""
    logger.error(f"未处理的异常: {str(exc)}", exc_info=True)
    return JSONResponse(
        status_code=HTTP_200_OK,
        content={
            "code": CODE_ERROR,
            "message": "服务器内部错误",
            "data": None
        }
    )
